package com.unlcn.erp.hyc.interfaces.backend.service;


import com.alibaba.fastjson.JSONObject;
import com.unlcn.erp.hyc.interfaces.backend.bo.PayBillDetail;
import com.unlcn.erp.hyc.interfaces.backend.bo.PayBillMain;
import com.unlcn.erp.hyc.interfaces.backend.bo.PayCodesDB;
import com.unlcn.erp.hyc.interfaces.backend.enums.CallHYCUrlTypeEnum;
import com.unlcn.erp.hyc.interfaces.base.mapper.*;
import com.unlcn.erp.hyc.interfaces.base.model.*;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

import static org.springframework.beans.BeanUtils.copyProperties;

/**
 * Created by zoupx on 2017-09-08.
 */
@Service
public class CallPayCodesServiceImpl implements CallPayCodesService {
    private static final Logger LOGGER = LoggerFactory.getLogger(CallPayCodesServiceImpl.class);
    @Autowired
    private CallHYCUrlReceiveService callHYCUrlReceiveService;
    @Autowired
    private  SmpaycodesmainMapper  smpaycodesmainMapper;
    @Autowired
    private SmpaycodesdetailMapper smpaycodesdetailMapper;
    @Autowired
    private ArpayshipMapper arpayshipMapper;
    @Autowired
    private SoshipheadMapper soshipheadMapper;
    @Autowired
    private SoshiplineMapper soshiplineMapper;
    @Autowired
    private SoorderMapper soorderMapper;
    @Autowired
    private ArpaylistMapper arpaylistMapper;
    @Autowired
    private HycwaybillMapper hycwaybillMapper;
    @Autowired
    private HycwaybilldetailMapper hycwaybilldetailMapper;
    @Autowired
    private CheckIntermediateService checkIntermediateService;
    @Autowired
    private HycExceptionMsgMapper hycExceptionMsgMapper;
    @Autowired
    private ExecptionDisposeService execptionDisposeService;


    private static final String  PAYCODES = "PAYCODES" ,PAYDETAIL = "PAYDETAIL";

    @Override
    public void updateArpayship() throws Exception {

        SmpaycodesmainExample  smpaycodesmainExample=new SmpaycodesmainExample();
        smpaycodesmainExample.createCriteria().andVcflagEqualTo("0");
        List <Smpaycodesmain>  list=smpaycodesmainMapper.selectByExample(smpaycodesmainExample);
        LOGGER.debug("查询出应付主表数据量"+list.size());
        if(CollectionUtils.isNotEmpty(list)){
            DealPayMain(list);
        }
    }

    //处理主数据
    public void DealPayMain(List<Smpaycodesmain> list) throws Exception{
        for(int i = 0; i < list.size() ; i++ ){
            Smpaycodesmain smpaycodesmain = list.get(i);
            Boolean isflag = DealPayDetail(smpaycodesmain);
            // 更新主表狀態為1
            if(isflag){
                smpaycodesmainMapper.updateByIlineid(smpaycodesmain.getIlineid());
                LOGGER.info(smpaycodesmain.getBillcode()+"应付账单保存成功");
            }
        }
    }

    //处理明细数据
    public Boolean DealPayDetail(Smpaycodesmain smpaycodesmain) throws Exception{
        int isFlag = 0;
        LOGGER.debug("查询出应付明细表数据量"+smpaycodesmain.getBillcode());
        SmpaycodesdetailExample smpaycodesdetail =new SmpaycodesdetailExample();
        smpaycodesdetail.createCriteria().andBillcodeEqualTo(smpaycodesmain.getBillcode()).andVcflagEqualTo("0");
        List<Smpaycodesdetail>  list=smpaycodesdetailMapper.selectByExample(smpaycodesdetail);
        for(int i = 0; i < list.size() ; i++ ){
            Smpaycodesdetail  detail = list.get(i);
           // ArpayshipSo arpayshipSoParm=new ArpayshipSo();
            //上生產環境
            //arpayshipSoParm.setVcorderno();
            //arpayshipSoParm.setVcorderno("L16001610");
            //arpayshipSoParm.setVccustshipno("201701101721");

            List<ArpayshipSo>   payshipSoList=arpayshipMapper.selectByVcorderno(detail.getServiceordercode());
            LOGGER.debug("查询出应付数据量payshipSoList"+payshipSoList.size());
            if(payshipSoList.size() == 0) continue;
            //取出对象值
            ArpayshipSo  pay=payshipSoList.get(0);
            Arpayship arpayshipSave=new Arpayship();
            arpayshipSave.setIshiplineid(pay.getIshiplineid());
            arpayshipSave.setIshipid(pay.getIshipid());
            arpayshipSave.setIorderid(Integer.valueOf(pay.getSoilineid()));
            arpayshipSave.setDcshipqty(1);
            arpayshipSave.setDckilometer(1);
            arpayshipSave.setDcprice(Double.parseDouble(detail.getSettlecost()));
            LOGGER.debug("查询出应付数据量getIcustshipid"+pay.getIcustshipid());
            arpayshipSave.setIcustshipid(pay.getIcustshipid());
            arpayshipSave.setVccustshipno(pay.getVccustshipno());
            arpayshipSave.setDtshipprint(pay.getDtshipprint());
            arpayshipSave.setDtshipreceive(pay.getDtshipreceive());
            arpayshipSave.setDctotal(Double.parseDouble(detail.getSettlecost()));

            arpayshipSave.setIcheck(1);
            arpayshipSave.setDtcheck(new Date());
            arpayshipSave.setVccheckuserno("system");
            if("30".equals(smpaycodesmain.getBillstatus()) && "30".equals(smpaycodesmain.getPaystatus())){
                arpayshipSave.setDcpayed(Double.parseDouble(detail.getSettlecost()));
                arpayshipSave.setDtpay(new Date(Long.parseLong(smpaycodesmain.getGmtmodified())));
                arpayshipSave.setVcinvoiceuser(smpaycodesmain.getModifieduser());
            }

            List<ArpayshipSo>  existpayship=arpayshipMapper.selectByIshiplineid(pay.getIshiplineid());
            if (existpayship.size()>0)  {
                arpayshipMapper.updateByIshiplineid(arpayshipSave);
            }else  {
                arpayshipMapper.insertArpayship(arpayshipSave);
            }
            //更新明細狀態為1
            smpaycodesdetailMapper.updateByIlineid(detail.getIlineid());
            isFlag ++;
        }

        if(isFlag == list.size()){
            return true;
        }
        return false;

    }



    @Override
    public void getPayCodes() throws Exception {
        //查询慧运车最新被修改的应付账单号列表。
        String data = callHYCUrlReceiveService.callHYCUrlReceive(PAYCODES, null);
        //将接口返回的数据进行拆分；
        List<PayCodesDB> payCodesDB= JSONObject.parseArray(data,PayCodesDB.class);
        if(CollectionUtils.isNotEmpty(payCodesDB)){
            for(int i = 0; i < payCodesDB.size() ; i++ ){
                PayCodesDB payCodes = payCodesDB.get(i);
                LOGGER.debug("得到应付账单号列表"+payCodes.getCode());
                PayDetail(payCodes.getCode());
            }
        }
    }



    /**
     *获取提交应付账单明細
     * @param
     */
    public void PayDetail(String code) throws Exception{
        //根据订单号获取订单详细信息
        String data = callHYCUrlReceiveService.callHYCUrlReceive(PAYDETAIL,code);
        PayBillMain db = JSONObject.parseObject(data, PayBillMain.class);
         savePayBillMain(db);
    }

    /**
     * 保存数据主表中
     * @param db  数据
     */
    public void savePayBillMain(PayBillMain db){
        Smpaycodesmain smpaycodesmain = new Smpaycodesmain();

        copyProperties(db,smpaycodesmain);
        //转换Comment
        if (null!=db.getcomment()){
            smpaycodesmain.setComments(db.getcomment());
        }
        smpaycodesmainMapper.insertPayMain(smpaycodesmain);
         savePayDetail(db.getBillDetailList());
    }

    /**
     * 保存数据明細中
     * @param db  数据
     */
    public void savePayDetail(List<PayBillDetail> db){
        for(int i = 0; i < db.size() ; i++ ){
            Smpaycodesdetail smpaycodesdetail = new Smpaycodesdetail();
            PayBillDetail payBillDetail = db.get(i);
            BeanUtils.copyProperties(payBillDetail,smpaycodesdetail);
            //转换Comment
            if (null!=payBillDetail.getcomment()){
                smpaycodesdetail.setComments(payBillDetail.getcomment());
            }
            LOGGER.debug("得到应收车vehicleName"+smpaycodesdetail.getVehiclename());
            smpaycodesdetail.setVcflag("0");
            smpaycodesdetailMapper.insertPayDetail(smpaycodesdetail);
        }
    }

    /**
     * 检查账单是否到账
     * @throws Exception
     */
    @Override
    public void checkAccoun() throws Exception {
        //检查所有的慧运车账单

        List<Smpaycodesdetail> list = smpaycodesdetailMapper.getAllByNotAccount();
        if(CollectionUtils.isNotEmpty(list)){
            for (Smpaycodesdetail smpaycodesdetail : list) {
                //获取账单状态
                try{
                    List<Smpaycodesmain> mainList = smpaycodesmainMapper.getStatusByBillcode(smpaycodesdetail.getBillcode());
                    if(CollectionUtils.isNotEmpty(mainList)){
                        Smpaycodesmain smpaycodesmain = mainList.get(0);
                        if("30".equals(smpaycodesmain.getPaystatus()) && "20".equals(smpaycodesmain.getBillstatus())){
                            String waybillCode = smpaycodesdetail.getWaybillcode();
                            //检查运单信息
                            SoshipheadExample example = new SoshipheadExample();
                            example.createCriteria().andVcshipnoEqualTo(waybillCode);
                            List<Soshiphead> shipheadList = soshipheadMapper.selectByExample(example);
                            if(CollectionUtils.isNotEmpty(shipheadList)){
                                Soshiphead soshiphead = shipheadList.get(0);
                                Long shipId = soshiphead.getIlineid();
                                List<Soshipline> soshiplineList = soshiplineMapper.getWaybillByShipID(shipId);
                                if(CollectionUtils.isNotEmpty(soshiplineList)){
                                    for (Soshipline soshipline : soshiplineList) {
                                        Long shiplineid = soshipline.getIlineid();
                                        Arpayship arpayship = arpayshipMapper.getPayShipByShipLine(shiplineid);
                                        if(arpayship != null){
                                            this.updatePayShipByPayship(arpayship);

                                        }
                                    }
                                }
                            }else {//说明该运单交给中联托运
                                Soorder soorder = soorderMapper.getOrderByOrderNo(smpaycodesdetail.getServiceordercode());
                                //判断该订单是否已经被拆分
                                List<Soorder> soorderList = soorderMapper.judgeChildOrdersByIpid(soorder.getIlineid());
                                if(CollectionUtils.isNotEmpty(soorderList)){
                                    for (Soorder soorder1 : soorderList) {
                                        Arpayship arpayship = arpayshipMapper.getPayshipByOrderId(soorder1.getIlineid());
                                        this.updatePayShipByPayship(arpayship);
                                    }
                                }else{//说明该订单没有子订单
                                    //找到该订单对应的账单
                                    Arpayship arpayship = arpayshipMapper.getPayshipByOrderId(soorder.getIlineid());
                                    this.updatePayShipByPayship(arpayship);
                                }
                            }
                            //进行标记
                            smpaycodesdetail.setIsaccount(1);
                            smpaycodesdetail.setDtaccount(new Date());
                            smpaycodesdetailMapper.updateAccount(smpaycodesdetail);

                        }
                    }
                }catch (NullPointerException e){
                    LOGGER.error("未找到对应的应付账单账号："+smpaycodesdetail.getBillcode());
                    throw  new Exception(e);
                }

            }
        }
    }

    /**
     *  根据订单号修改支付账单价格
     * @param arpayship
     */
    private void updatePayShipByPayship(Arpayship arpayship) throws Exception{
        //获取支付账单
        arpayship.setDcpayed(arpayship.getDctotal());
        arpayship.setDtpay(new Date());
        arpayship.setVcinvoiceuser("system");
        arpayship.setIpaystatus(2);
        arpayshipMapper.updateCheckAccoun(arpayship);
        //写进付款记录表中
        Arpaylist payList = new Arpaylist();
        payList.setIpaylineid(arpayship.getIlineid());
        payList.setDcpay(arpayship.getDctotal());
        payList.setVcuserno("system");
        payList.setVcpayno("HYC");
        arpaylistMapper.savePayList(payList);

    }


    /**
     *检查账单是否到账
     * @throws Exception
     */
    @Override
    public void markersOfBill() throws Exception{
        //查询所有的慧运车交给中联的订单
        List<Hycwaybill> waybillList = hycwaybillMapper.getWaybillByNotAccountAndZL();
        if(CollectionUtils.isNotEmpty(waybillList)){
            for (Hycwaybill hycwaybill : waybillList) {
                try {
                    int i = 0;
                    //找到对应的明细订单
                    List<Hycwaybilldetail> waybilldetailList = hycwaybilldetailMapper.getOrderCodeByWaybillCode(hycwaybill.getWaybillcode());
                    for (Hycwaybilldetail hycwaybilldetail : waybilldetailList) {
                        //System.out.println(hycwaybilldetail.getWaybillcode()+"~~~~~"+hycwaybilldetail.getOrdercode());
                        Long orderCode = 0L;
                        //找到对应的订单
                        Soorder soorder = soorderMapper.getOrderByOrderNo(hycwaybilldetail.getOrdercode());
                        if (soorder != null) {
                            String startCity = checkIntermediateService.switchCityName(hycwaybill.getDepartcityname());
                            String endCity = checkIntermediateService.switchCityName(hycwaybill.getReceiptcityname());

                            if (1 == hycwaybilldetail.getServicedispatchtimes() && startCity.equals(soorder.getVcstartcity()) && endCity.equals(soorder.getVccityname())) {
                                orderCode = soorder.getIlineid();

                            } else {
                                soorder = soorderMapper.getOrderByOrderNo(hycwaybilldetail.getServicedispatchtimes() + hycwaybilldetail.getOrdercode());
                                orderCode = soorder.getIlineid();
                            }
                            //找到对应的运单明细ID
                            Long shipid = soshiplineMapper.getLineIdByOrderId(orderCode);
                            if (shipid != null) {
                                Arpayship arpayship = arpayshipMapper.getPayShipByShipLine(shipid);
                                if (arpayship != null) {
                                    if (arpayship != null && arpayship.getIpaystatus() < 2 && arpayship.getBinvoice() == 1 && arpayship.getBinvoicecheck() == 1) {
                                        this.updatePayShipByPayship(arpayship);
                                        i++;
                                    }
                                }
                            }
                        }
                    }
                    if (waybilldetailList.size() == i && i != 0) {
                        hycwaybill.setIsaccount(1);
                        hycwaybill.setDtaccount(new Date());
                        hycwaybillMapper.updateByPrimaryKey(hycwaybill);
                    }
                }catch (Exception e){
                    execptionDisposeService.saveExecption(e.toString(),hycwaybill.getWaybillcode(),CallHYCUrlTypeEnum.HYC_MARKERSOFBULL.getValue());
                    LOGGER.error("检查账单是否到账:"+hycwaybill.getWaybillcode()+"异常信息："+e.toString());
                }
            }
        }
    }

    /**
     * 将应付金额存入到soshipline中
     * @throws Exception
     */
    public void paymentAmount() throws Exception{
        //1、查询所有惠运车给中联的订单
        List<Hycwaybill> waybillList = hycwaybillMapper.getWaybillByNotAmountAndZL();
        if(CollectionUtils.isNotEmpty(waybillList)) {
            for (Hycwaybill hycwaybill : waybillList) {
                try{
                    int i = 0;
                    //找到对应的明细订单
                    List<Hycwaybilldetail> waybilldetailList = hycwaybilldetailMapper.getOrderCodeByWaybillCode(hycwaybill.getWaybillcode());
                    for (Hycwaybilldetail hycwaybilldetail : waybilldetailList) {
                        //System.out.println(hycwaybilldetail.getWaybillcode()+"~~~~~"+hycwaybilldetail.getOrdercode());
                        Long orderCode = 0L;
                        //找到对应的订单
                        Soorder soorder = soorderMapper.getOrderByOrderNo(hycwaybilldetail.getOrdercode());
                        if(soorder != null) {
                            String startCity = checkIntermediateService.switchCityName(hycwaybill.getDepartcityname());
                            String endCity = checkIntermediateService.switchCityName(hycwaybill.getReceiptcityname());
                            //2、判断一次调度还是多次调度
                            if (1 == hycwaybilldetail.getServicedispatchtimes() && soorder.getVcorderno().indexOf("SO") == 0 && startCity.equals(soorder.getVcstartcity()) && endCity.equals(soorder.getVccityname())) {
                                //3、一次调度自动将金额写入到soshipline中
                                orderCode = soorder.getIlineid();
                                //判断该指令是否已被调度
                                Long shiplineId= soshiplineMapper.getLineIdByOrderId(orderCode);
                                if(shiplineId != null && shiplineId != 0 ){
                                    //将金额修改到运单上
                                    Soshipline soshipline = new Soshipline();
                                    soshipline.setIorderid2(orderCode);
                                    soshipline.setDcpaycost(hycwaybilldetail.getUnitcost());
                                    soshipline.setIpaycosttype(1);
                                    soshiplineMapper.updatePayCostByOrderId(soshipline);
                                    i++;
                                }
                            }
                        }
                    }
                    if(waybilldetailList.size() == i && i != 0){
                        hycwaybill.setIsamount(1);
                        hycwaybill.setDtamount(new Date());
                        hycwaybillMapper.updateByPrimaryKey(hycwaybill);
                    }
                }catch (Exception e){
                    execptionDisposeService.saveExecption(e.toString(),hycwaybill.getWaybillcode(),CallHYCUrlTypeEnum.HYC_PAYMENTAMOUNT.getValue());
                    LOGGER.error("检查账单是否到账:"+hycwaybill.getWaybillcode()+"异常信息："+e.toString());
                }
            }
        }
    }

    @Override
    public void paymentAmount(String waybillcode) throws Exception {
        HycwaybillExample example = new HycwaybillExample();
        example.createCriteria().andWaybillcodeEqualTo(waybillcode);

        List<Hycwaybill> waybillList = hycwaybillMapper.selectByExample(example);
        if(CollectionUtils.isNotEmpty(waybillList)) {
            Hycwaybill hycwaybill = waybillList.get(0);
                try{
                    int i = 0;
                    //找到对应的明细订单
                    List<Hycwaybilldetail> waybilldetailList = hycwaybilldetailMapper.getOrderCodeByWaybillCode(hycwaybill.getWaybillcode());
                    for (Hycwaybilldetail hycwaybilldetail : waybilldetailList) {
                        //System.out.println(hycwaybilldetail.getWaybillcode()+"~~~~~"+hycwaybilldetail.getOrdercode());
                        Long orderCode = 0L;
                        //找到对应的订单
                        Soorder soorder = soorderMapper.getOrderByOrderNo(hycwaybilldetail.getOrdercode());
                        if(soorder != null) {
                            String startCity = checkIntermediateService.switchCityName(hycwaybill.getDepartcityname());
                            String endCity = checkIntermediateService.switchCityName(hycwaybill.getReceiptcityname());
                            //2、判断一次调度还是多次调度
                            if (1 == hycwaybilldetail.getServicedispatchtimes() && soorder.getVcorderno().indexOf("SO") == 0 && startCity.equals(soorder.getVcstartcity()) && endCity.equals(soorder.getVccityname())) {
                                //3、一次调度自动将金额写入到soshipline中
                                orderCode = soorder.getIlineid();
                                //判断该指令是否已被调度
                                Long shiplineId= soshiplineMapper.getLineIdByOrderId(orderCode);
                                if(shiplineId != null && shiplineId != 0 ){
                                    //将金额修改到运单上
                                    Soshipline soshipline = new Soshipline();
                                    soshipline.setIorderid2(orderCode);
                                    soshipline.setDcpaycost(hycwaybilldetail.getUnitcost());
                                    soshipline.setIpaycosttype(1);
                                    soshiplineMapper.updatePayCostByOrderId(soshipline);
                                    i++;
                                }
                            }
                        }
                    }
                    if(waybilldetailList.size() == i && i != 0){
                        hycwaybill.setIsamount(1);
                        hycwaybill.setDtamount(new Date());
                        hycwaybillMapper.updateByPrimaryKey(hycwaybill);
                    }
                }catch (Exception e){
                    execptionDisposeService.saveExecption(e.toString(),hycwaybill.getWaybillcode(),CallHYCUrlTypeEnum.HYC_PAYMENTAMOUNT.getValue());
                    LOGGER.error("检查账单是否到账:"+hycwaybill.getWaybillcode()+"异常信息："+e.toString());
                }
            }
    }
}
